<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <span slot="before">共{{ page.total }}条记录</span>
        <template slot="after">
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportEmployees">导出</el-button>
          <el-button v-if="checkPoints('addEmployee')" size="small" type="primary" @click="showDialog = true">新增员工</el-button>
        </template>
      </page-tools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" type="index" sortable="">
            <template #default="scoped">
              {{ ((page.page - 1) * page.size) + (scoped.$index + 1) }}
            </template>
          </el-table-column>
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column label="头像">
            <template slot-scope="{row}">
              <el-row style="text-align: center;">
                <img
                  v-imgerr="require('@/assets/common/bigUserHeader.png')"
                  :src="row.staffPhoto"
                  alt=""
                  class="avatar"
                  @click="showImage(row.staffPhoto)"
                >
              </el-row>
            </template>
          </el-table-column>
          <el-table-column label="聘用形式" prop="formOfEmployment" :formatter="formOfEmployment" sortable="" />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template slot-scope="scope">
              {{ scope.row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.enableState === 1"
              />
              <!-- active-color="#13ce66"
              inactive-color="#ff4949" -->
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <!-- <template #default="{row}"> -->
            <template #default="{row}">
              <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="showAssignRole(row.id)">角色</el-button>
              <el-button type="text" size="small" @click="delEmp(row.id)">删除</el-button>
              <!-- <el-button type="text" size="small" @click="delEmp(row.id)">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :page-size="page.size"
            :total="page.total"
            layout="prev, pager, next"
            @current-change="currentChange"
          />
        </el-row>
      </el-card>
    </div>
    <AddEmployee :show-dialog.sync="showDialog" @handleClose="HandleClose" />

    <el-dialog title="头像预览" :visible="showImgDialog" @close="showImgDialog = false">
      <el-row type="flex" justify="center">
        <canvas ref="imgCanvas" />
      </el-row>
    </el-dialog>

    <AssignRole ref="assignRole" :user-id="userId" :show-role-dialog.sync="showRoleDialog" />
  </div>
</template>

<script>
import { getEmployeeList, delEmployee } from '@/api/employee'
import employeeEnum from '@/api/constant/employees'
import AddEmployee from './component/addEmployee'
import AssignRole from './component/assignRole'
import { formatDate } from '@/filters'
import QRcode from 'qrcode'
export default {
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [],
      page: {
        page: 1,
        size: 4,
        total: 0
      },
      showDialog: false,
      showImgDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    HandleClose(isAdd) {
      this.showDialog = false
      if (isAdd) {
        this.getEmployeeList()
      }
    },
    async exportEmployees() {
      const { export_json_to_excel } = await import('@/vender/Export2Excel')
      // console.log(export_json_to_excel)
      const dict = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      // console.log(Object.keys(dict))
      this.page.page = 1
      this.page.size = this.page.total
      const { rows } = await getEmployeeList(this.page)
      // console.log(rows)
      const userData = rows.map(user => {
        return this.objectArr(user, dict)
      })
      // console.log(userData)
      export_json_to_excel({
        header: Object.keys(dict),
        data: userData
      })
      // export_json_to_excel({
      //   header: ['姓名', '年龄', '地址'],
      //   data: [
      //     ['小明', 888, '珠吉路58号'],
      //     ['小红', 8, '珠吉路59号'],
      //     ['小刚', 12, '珠吉路60号']
      //   ]
      // })
    },
    objectArr(user, dict) {
      const newUser = []
      // console.log(user)
      for (const key in dict) {
        // console.log(key)
        const enKey = dict[key]
        const value = user[enKey]
        if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
          newUser.push(new Date(formatDate(value)))
        } else if (enKey === 'formOfEmployment') {
          const obj = employeeEnum.hireType.find(item => item.id === value)
          newUser.push(obj ? obj.value : '未知')
        } else {
          newUser.push(value)
        }
        // console.log(user[enKey])
      }
      return newUser
    },
    async getEmployeeList() {
      // console.log('list')
      const { total, rows } = await getEmployeeList(this.page)
      this.page.total = total
      this.list = rows
      // console.log(this.list)
    },
    currentChange(currIndex) {
      this.page.page = currIndex
      this.getEmployeeList()
    },
    formOfEmployment(row, column, cellValue, index) {
      // console.log(row, column, cellValue, index)
      // console.log(cellValue)
      // return cellValue === 1 ? '正式员工' : '临时工'
      const obj = employeeEnum.hireType.find(item => item.id === Number(cellValue))
      return obj ? obj.value : '未知'
    },
    async delEmp(id) {
      try {
        if (this.page.page > 1 && this.list.length === 1) {
          this.page.page--
        }
        const res = await delEmployee(id)
        console.log(res)
        this.$message.success('删除员工成功')
        this.getEmployeeList()
      } catch (error) {
        console.log(error)
      }
    },
    formatDate(numb, format) {
      const time = new Date((numb - 1) * 24 * 3600000 + 1)
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + month + format + date
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    },
    showImage(url) {
      if (url) {
        this.showImgDialog = true
        this.$nextTick(() => {
          QRcode.toCanvas(this.$refs.imgCanvas, url)
        })
      }
    },
    async showAssignRole(id) {
      // console.log(id)
      await this.$refs.assignRole.getUserDetail(id)
      this.showRoleDialog = true
      this.userId = id
    },
    checkPoints(pointName) {
      return this.$store.getters.roles && this.$store.getters.roles.points.includes(pointName)
    }
  }
}
</script>

<style lang="scss" scoped>
.avatar{
  width: 150px;
  height: 150px;
  object-fit: contain;
}
</style>

